#-*- coding:utf-8 -*-
'''
Created on Jun 24, 2012

@author: bbg
'''

from core.db.company_management.company import Company
import json
import uuid
from core.util.debug import Log
from webob import Request, Response
from service.server_config import SrvConfig

def application(environ, start_response):
    '''
        entrance of apache wsgi application
    '''    
    req = Request(environ)
    res = Response()
    
    ApplyService.process(req, res)
    
    return res(environ, start_response)    
   

class ApplyService(object):
    __setup__ = False
    log = None    

    @staticmethod
    def process(req, res):
        if ApplyService.__setup__ == False:
            Log.setPath(SrvConfig.getLogPath())
            ApplyService.log = Log()            
            ApplyService.__setup__ = True  
                    
        try:
            dbsession = SrvConfig.getDefaultDBSession()
            applyService = ApplyService(dbsession)            
            applyService.applayCompanyRegister(req, res)
        except Exception, e:
            res.json = {'ret':-1, 'msg':'excetpion'}
            ApplyService.log.e('ApplyService:process, exception %s' % e)
        finally:
            dbsession.close()
    
    def __init__(self, dbsession):
        self.dbsession = dbsession

    def applayCompanyRegister(self, req, res):
        '''
            负责公司层面申请注册
        '''             
        name = req.params['name']
        address = req.params['address']        
        yyzz = req.params['yyzz']
        contact = req.params['contact']
        phone = req.params['phone']
        jytype = req.params['jytype']
        jyguimo = req.params['jyguimo']    
        email= req.params['email']
         
        #核实企业ID是否存在
        if self._hasApplied(name,yyzz,contact,phone) is True:        
            ApplyService.log.e("ApplyService.applayCompanyRegister: already exist, name:%s, address:%s" % (name, address))            
            res.json = {'ret':-1, 'msg':'already exist'}
                         
        tempuuid = uuid.uuid4()
        company = Company()      
        company.name = name
        company.address = address
        company.contact = contact
        company.phone = phone
        company.jytype = jytype
        company.email = email
        company.jyguimo = jyguimo
        company.yyzz = yyzz
        company.uuid = tempuuid
        
        self.dbsession.add(company)
        self.dbsession.commit()
        
        companyb = self.dbsession.query(Company).filter(Company.uuid == tempuuid)
        self.dbsession.commit()
        response_paramsARRAY = []   
        for row in companyb:
            response_paramsb = {}
            response_paramsb["ret"]=0
            response_paramsb["msg"]="申请已经提交，企业ID：%d "  % row.id
            strtemp=json.dumps(response_paramsb)
            response_paramsARRAY.append(strtemp)      
                
        res.json = response_paramsARRAY
        
    
    def _hasApplied(self, name,yyzz,contact,phone):
        '''
            validate apply
        '''
        try:
            result = self.dbsession.query(Company).filter(Company.name == name and Company.phone == phone)                
            self.dbsession.commit()
            if result.count() > 0:      
                return True;
        except:
            return True
             
        return False
 
 


        